package yqRouter

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
	"go-yuque/logger"
	"net/http"
	"time"
)

// 已延期的 session
var updatedSessionMap = make(map[string]int64)

func init() {
	// 定期更新 session
	go func() {
		ticker := time.NewTicker(5 * time.Second)
		for {
			select {
			case <-ticker.C:
				// 如果存在于 Set 中, 判断时间是否超过当前时间-10min
				for k := range updatedSessionMap {
					if time.Now().Unix()-updatedSessionMap[k] > (10 * 60) {
						delete(updatedSessionMap, k)
						logger.Infof("[updatedSessionMap]session已过期,id:%s", k)
					}
				}
			}
		}
	}()
}

func InitPageRouter(router *gin.Engine) {
	pageRouter := router.Group("/page")

	{
		pageRouter.GET("", hello)
		pageRouter.GET("/", index)
		pageRouter.GET("/index", index)
	}

}

func hello(c *gin.Context) {
	c.HTML(http.StatusOK, "hello/index.html", gin.H{
		"title": "Hello World",
		"user":  "张三",
	})
}

func index(c *gin.Context) {
	session := sessions.Default(c)
	yqCookie := session.Get("yqCookie")

	if yqCookie == nil {
		yqCookie = ""
	} else {
		// 刷新 session 时间
		id := sessionGetId(&session)

		session, _ := SessionStore.Get(c.Request, SessionIdCookieName)
		if _, sessionOk := updatedSessionMap[id]; !sessionOk {
			// 不存在于 map 中的才延期
			updatedSessionMap[id] = time.Now().Unix()
			session.Flashes()
			session.Options.MaxAge = 3600 * 24 * 7
			session.Save(c.Request, c.Writer)
			logger.Infof("延期 session: %s", id)
		}

	}

	c.HTML(http.StatusOK, "yuque/index.html", gin.H{
		"yqCookie": yqCookie,
	})
}
